package com.scholarship.system.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * JWT工具类
 */
@Component
public class JwtUtil {

    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 生成token
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        String token = createToken(claims, userDetails.getUsername());
        log.info("为用户 {} 生成新的令牌", userDetails.getUsername());
        return token;
    }

    /**
     * 从token中提取用户名
     */
    public String extractUsername(String token) {
        try {
            String username = extractClaim(token, Claims::getSubject);
            log.debug("从令牌中提取的用户名: {}", username);
            return username;
        } catch (Exception e) {
            log.error("从令牌中提取用户名时发生错误", e);
            return null;
        }
    }

    /**
     * 从token中提取过期时间
     */
    public Date extractExpiration(String token) {
        try {
            return extractClaim(token, Claims::getExpiration);
        } catch (Exception e) {
            log.error("从令牌中提取过期时间时发生错误", e);
            return new Date(0); // 返回一个很久以前的日期，表示已过期
        }
    }

    /**
     * 从token中提取claim
     */
    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 从token中提取所有claim
     */
    private Claims extractAllClaims(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            log.error("令牌已过期: {}", token);
            throw e;
        } catch (Exception e) {
            log.error("解析令牌时发生错误: {}", e.getMessage());
            throw e;
        }
    }

    /**
     * 判断token是否过期
     */
    private Boolean isTokenExpired(String token) {
        try {
            final Date expiration = extractExpiration(token);
            boolean isExpired = expiration.before(new Date());
            if (isExpired) {
                log.debug("令牌已过期，过期时间: {}", expiration);
            }
            return isExpired;
        } catch (Exception e) {
            log.error("检查令牌过期时发生错误", e);
            return true;
        }
    }

    /**
     * 创建token
     */
    private String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);
        log.debug("创建令牌: 主题={}, 有效期从{}到{}", subject, now, expiryDate);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    /**
     * 验证token
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        try {
            if (token == null || token.isEmpty()) {
                log.warn("传入的令牌为空，验证失败");
                return false;
            }

            // 如果userDetails为null，只检查token是否解析正常且未过期
            if (userDetails == null) {
                try {
                    String username = extractUsername(token);
                    boolean notExpired = !isTokenExpired(token);
                    log.debug("仅检查令牌有效性: 用户名={}, 是否未过期={}", username, notExpired);
                    return username != null && notExpired;
                } catch (Exception e) {
                    log.error("令牌格式无效", e);
                    return false;
                }
            }

            // 完整验证：检查用户名匹配且未过期
            final String username = extractUsername(token);
            boolean isValid = username != null &&
                    username.equals(userDetails.getUsername()) &&
                    !isTokenExpired(token);

            log.debug("验证令牌: token用户名={}, 实际用户名={}, 是否有效={}",
                    username, userDetails.getUsername(), isValid);

            return isValid;

        } catch (Exception e) {
            log.error("验证令牌时发生未预期错误", e);
            return false;
        }
    }
}